package cn.com.kblog.util;


import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.com.kblog.common.Constant;
import cn.com.kblog.model.User;




/**
 * 用户登录工具类
 * @author KK.Luo
 * Email luokai8@vip.qq.com
 * @date 2013-12-2下午9:33:01
 */
public class LoginUtils {
	/** 当前请求的request */
    private static final ThreadLocal<HttpServletRequest> THREAD_REQUST = new ThreadLocal<HttpServletRequest>();
    /** 当前请求的response */
    private static final ThreadLocal<HttpServletResponse> THREAD_RESPONSE = new ThreadLocal<HttpServletResponse>();
    
    /**
     * 用户登录凭证相关
     */
    private static final String LOGIN_USER_KEY = CryptUtils
	    .encrypt("LOGIN_USER_KEY",Constant.CRYPT_KEY);
    
    /**
     * 初始化上下文环境
     * @param request
     * @param response
     */
    public static void initConext(final HttpServletRequest request,
	    final HttpServletResponse response) {
		THREAD_REQUST.set(request);
		THREAD_RESPONSE.set(response);
    }
    /**
     * 清理上下文环境
     */
    public static void clearContext() {
		THREAD_REQUST.remove();
		THREAD_RESPONSE.remove();
    }
    
    
    /**
     * 获取request对象
     * @return
     */
    public static HttpServletRequest getRequest() {
    	return THREAD_REQUST.get();
    }
   
    /**
     * 获取Response对象
     * @return 
     */
    public static HttpServletResponse getResponse() {
    	return THREAD_RESPONSE.get();
    }
    
    
    public static void logout(){
    	_removeSessionAttr(LOGIN_USER_KEY);
    	_removeCookieAttr(LOGIN_USER_KEY);
    }
    
    private static void _removeCookieAttr(String loginUserKey) {
    	_setCookie(loginUserKey, null, 0, "/admin", null);
		
	}
	/**
     * 普通登录
     * @param username
     * @param password
     * @return
     */
    public static boolean login(String username,String password){
    	//数据加密后的数据
    	password = CryptUtils.encrypt(password,Constant.CRYPT_KEY);
    	// 获取登录用户信息
    	User user = User.dao.login(username,password);
    	if (null == user) {
    	    return false;
    	}
    	//更新登录时间
    	User db_user = User.dao.login(username,password);
    	db_user.updateLastLoginTime();
    	_setSessionAttr(LOGIN_USER_KEY, user);
    	return true;
    	
    }
    
    /**
     * “记住我”登录
     * @param username
     * @param password
     * @return
     */
    public static boolean login2remenber(String username,String password){
    	//数据加密后的数据
    	password = CryptUtils.encrypt(password,Constant.CRYPT_KEY);
    	// 获取登录用户信息
    	User user = User.dao.login(username,password);
    	if (null == user) {
    	    return false;
    	}
    	//更新登录时间
    	user.updateLastLoginTime();
    	_setSessionAttr(LOGIN_USER_KEY, user);
    	_setCookie(LOGIN_USER_KEY,""+ user.getID(), 60*60*24*30*365, "/admin", AppConfigUtil.get("domain"));
    	return true;
    }
    
    /**
     * 获得登录用户
     * @return
     */
    public static User getLoginUser(){
    	return (User)_getSessionAttr(LOGIN_USER_KEY);
    }
    /**
     * 获得Cookile的登录用户
     * @return
     */
    public static User getLoginUserFromCookie(){
    	Cookie cookie = _getCookieByName(LOGIN_USER_KEY);
    	if(cookie==null){
    		return null;
    	}
    	String userId =  cookie.getValue();
    	if(userId==null){
    		return null;
    	}
    	User user = User.dao.findById(new Integer(userId));
    	return user;
    }
    /**
     * 判断用户是否登录
     * @return
     */
    public static boolean isLogin(){
    	User sessionUser  = getLoginUser();
    	if(sessionUser!=null){
    		return true;
    	}
    	User cookieUser = getLoginUserFromCookie();
    	if(cookieUser!=null){
    		//更新登录时间
    		cookieUser.updateLastLoginTime();
    		_setSessionAttr(LOGIN_USER_KEY, cookieUser);
    		return true;
    	}
    	return false;
    }
    /**
	 * 设置Cookie
	 * @param response
	 * @param name
	 * @param value
	 * @param maxAgeInSeconds
	 * @param path
	 * @param domain
	 */
	private static void _setCookie(String name, String value, int maxAgeInSeconds, String path, String domain) {
		Cookie cookie = new Cookie(name, value);
		if (domain != null)
			cookie.setDomain(domain);
		cookie.setMaxAge(maxAgeInSeconds);
		cookie.setPath(path);
		getResponse().addCookie(cookie);
	}
	/**
	 * Store Object to session.
	 * @param key a String specifying the key of the Object stored in session
	 * @param value a Object specifying the value stored in session
	 */
	private static void _setSessionAttr(String key, Object value) {
		getRequest().getSession().setAttribute(key, value);
	}
	private static Object _getSessionAttr(String key) {
		return  getRequest().getSession().getAttribute(key);
	}
	/**
	 * Remove Object in session.
	 * @param key a String specifying the key of the Object stored in session
	 */
	private static void _removeSessionAttr(String key) {
		HttpSession session = getRequest().getSession(false);
		if (session != null)
			session.removeAttribute(key);
	}
	
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	private static Cookie _getCookieByName(String name){
		Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
		HttpServletRequest request = getRequest();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    if(cookieMap.containsKey(name)){
	        Cookie cookie = (Cookie)cookieMap.get(name);
	        return cookie;
	    }else{
	        return null;
	    }   
	}
    
}
